package com.dongdongshop.service.impl;

import com.dongdongshop.domain.PageResult;
import com.dongdongshop.mapper.TbGoodsDescMapper;
import com.dongdongshop.mapper.TbGoodsMapper;
import com.dongdongshop.mapper.TbItemMapper;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
@DubboService
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private TbGoodsMapper tbGoodsMapper;
    @Resource
    private TbGoodsDescMapper tbGoodsDescMapper;
    @Resource
    private TbItemMapper tbItemMapper;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void addGoods(TbGoods tbGoods, TbGoodsDesc tbGoodsDesc, TbItem item) {
        tbGoodsMapper.insertSelective(tbGoods);
        tbGoodsDesc.setGoodsId(tbGoods.getId());
        tbGoodsDescMapper.insertSelective(tbGoodsDesc);
        item.setGoodsId(tbGoods.getId());
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        tbItemMapper.insertSelective(item);
    }

    @Override
    public PageResult<TbGoods> goodsList(TbGoods tbGoods, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<TbGoods> list = tbGoodsMapper.selectInfo(tbGoods);
        PageInfo page = new PageInfo(list);
        PageResult<TbGoods> pr = new PageResult<>();
        pr.setPageSize(pageSize);
        pr.setPageNum(pageNum);
        pr.setPages(page.getPages());
        pr.setRows(page.getList());
        pr.setTotal(page.getTotal());
        return pr;
    }

    @Override
    public void isShenhe(Long[] ids, TbGoods tbGoods) {
        if (tbGoods.getAuditStatus().equals("1")){
            rocketMQTemplate.convertAndSend("dongdongshop_topic",new Gson().toJson(ids));
        }
        tbGoodsMapper.isShenhe(ids,tbGoods);
    }

    @Override
    public void deleteById(Long[] ids) {
        tbGoodsMapper.deleteById(ids);
    }

    @Override
    public TbGoods selectByGoodsId(Long goodsId) {
        return tbGoodsMapper.selectByPrimaryKey(goodsId);
    }
}
